import {
  type ReactElement,
  type FC,
} from 'react'
import {
  Navigate,
  useLocation,
} from 'react-router-dom'
import {
  getToken,
  setRediectPath,
} from '@/library/tool-kits/handler-token'
import { REDIRECT_PATH_IF_HAS_LOGINING } from '@/library/tool-kits/get-process-env'
import { GlobalConstant } from '@/library/constants/globalConstant'

import { authenticationPaths } from '@/pages/authentication/paths'

interface AuthProps {
  children: ReactElement;
  auth: boolean;
}

export const AuthRouter: FC<AuthProps> = ({
  children,
  auth,
}) => {
  const { pathname } = useLocation()
  const hasAuthed = getToken()

  if (auth && hasAuthed) return children

  if (auth && !hasAuthed) {
    setRediectPath(pathname)
    return <Navigate to={authenticationPaths[`${GlobalConstant.PREFIX_FULLPATH}login`]} />
  }

  if (!auth && pathname.startsWith(authenticationPaths.basePagePath) && hasAuthed) {
    return <Navigate to={REDIRECT_PATH_IF_HAS_LOGINING} />
  }

  return children
}

export default AuthRouter
